package com.tutu.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;

/**
 * @Program: Spring_New
 * @Description: 实现执行方法的打印
 * @Author: JK.TuTu
 * @ @Version: 1.0
 * @Create: 2022-11-25 16:02
 **/
public class LogBeanPostProcessor implements BeanPostProcessor {


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //使用动态代理对目标bean进行增强，返回proxy对象，再存储到单例池singletonObjects中
        Object beanProxy = Proxy.newProxyInstance(
                bean.getClass().getClassLoader(),
                bean.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("方法" + method.getName() + "的开始时间:" + new Date());
                        Object result = method.invoke(bean, args);
                        System.out.println("方法" + method.getName() + "的结束时间:" + new Date());
                        return result;
                    }
                }
        );
        return beanProxy;
    }
}
